<template>
  <div class="bottom-nav">
    <template v-for="(item, index) in displayNavList" :key="index">
      <div class="bottom-nav-item" :class="{ 'logo-item': item.isLogo }" @click="handleNavClick(item, index)">
        <img :src="activeIndex === index ? item.activeIcon : item.icon" alt="">
        <span v-if="!item.isLogo">{{ item.title }}</span>
      </div>
    </template>
  </div>

  <!-- 店铺选择弹出层 -->
  <wd-popup v-model="showShopPopup" position="bottom">
    <view class="shop-popup">
      <view class="shop-popup-title">选择店铺</view>
      <view class="shop-list">
        <view
          v-for="(shop, idx) in myShopList"
          :key="idx"
          class="shop-item"
          @click="selectShop(shop)"
        >
          <image :src="shop.logo || '../static/imgs/NoPath.png'" class="shop-logo"></image>
          <view class="shop-info">
            <view class="shop-name">{{ shop.shopName }}</view>
            <view class="shop-type">{{ shop.shopType }}</view>
          </view>
          <wd-icon name="arrow-right" size="16px" color="#666"></wd-icon>
        </view>
      </view>
      <view class="close-btn" @click="showShopPopup = false">取消</view>
    </view>
  </wd-popup>
</template>

<script setup>
import { ref, watch, onMounted, computed } from 'vue'
import { storeToRefs } from 'pinia'
import { useBottomNavStore } from '@/stores/bottomNav'
// 获取用户数据
import { useUserStore } from '@/stores/user'

const userStore = useUserStore()
const bottomNavStore = useBottomNavStore()
const { activeIndex } = storeToRefs(bottomNavStore)
const emit = defineEmits(['change'])

// 使用 ref 创建本地变量存储店铺列表
const myShopList = ref([])
// 控制弹出层显示
const showShopPopup = ref(false)

// 纯 logo 配置
const logoItem = {
  icon: '../static/imgs/logo.jpg', // 请确保这个图片路径存在
  title: '',
  path: '',
  activeIcon: '../static/imgs/logo.jpg',
  isLogo: true
}

// 在组件挂载时从缓存加载数据
onMounted(() => {
  // 从本地缓存获取数据
  try {
    const cachedData = uni.getStorageSync('my-shop-list-cache')
    if (cachedData) {
      myShopList.value = JSON.parse(cachedData)
      console.log('bottomNav: 从缓存加载店铺数据成功', myShopList.value)
    } else {
      console.log('bottomNav: 缓存中没有店铺数据')
      // 如果缓存中没有数据，尝试使用 store 中的数据
      if (userStore.myShopList && userStore.myShopList.length > 0) {
        myShopList.value = userStore.myShopList
      }
    }
  } catch (error) {
    console.error('bottomNav: 读取缓存数据失败', error)
  }
})

// 同时监听 store 中的数据变化
watch(() => userStore.myShopList, (newVal) => {
  console.log('bottomNav: userStore.myShopList 变化', newVal)
  if (newVal && newVal.length > 0) {
    myShopList.value = newVal
  }
}, { deep: true })

const handleNavClick = (item, index) => {
  // 如果是 logo，显示提示信息
  if (item.isLogo) {
    uni.showToast({
      title: '更多功能，敬请期待',
      icon: 'none',
      duration: 2000
    })
    return
  }

  console.log(myShopList.value, 'myShopList');

  if (item.title === '我的店铺') {
    // 如果有店铺，弹出选择框
    if (myShopList.value && myShopList.value.length > 0) {
      showShopPopup.value = true
    } else {
      // 没有店铺时的处理
      uni.showToast({
        title: '您还没有店铺,请联系管理员添加店铺',
        icon: 'none'
      })
    }
  } else {
    // 其他导航项正常跳转
    navTo(item.path)
    bottomNavStore.setActiveIndex(index)
  }
  emit('change', index)
}

// 基于角色控制底部导航显示：商家(2)仅商家可见，接单大厅(1)仅骑手可见
const roleTypeId = computed(() => Number(userStore.customerInfo?.roleTypeId))
// 过滤后的导航列表，根据角色控制显示
const filteredNavList = computed(() => {
  const shopList = myShopList.value || []
  return navList.value.filter((item) => {
    if (item.title === '我的店铺') return (roleTypeId.value === 2 || roleTypeId.value === 4)&& shopList?.length > 0
    if (item.title === '接单大厅') return roleTypeId.value === 1
    return true
  })
})

// 添加 logo 后的显示列表
const displayNavList = computed(() => {
  const filtered = filteredNavList.value
  const logoPosition = filtered.length === 3 ? 1 : Math.floor(filtered.length / 2)

  const result = [...filtered]
  result.splice(logoPosition, 0, logoItem)

  return result
})

// 选择店铺
const selectShop = (shop) => {
  console.log('选择店铺', shop)
  showShopPopup.value = false
  // 导航到店铺页面
  uni.navigateTo({
    url: `/pages/shopManage?shopId=${shop.shopId}`
  })
  // 设置导航栏激活项
  bottomNavStore.setActiveIndex(1) // 假设"商家"的索引是1
}

const navList = ref([
  {
    icon: '../static/imgs/bottomNav/shouye1.png',
    title: '首页',
    path: '/pages/index',
    activeIcon: '../static/imgs/bottomNav/shouye2.png',
  },
  // {
  //   icon: '../static/imgs/bottomNav/shangjia1.png',
  //   title: '购物车',
  //   path: '/pages/MerchantList',
  //   activeIcon: '../static/imgs/bottomNav/shangjia2.png',
  // },
  {
    icon: '../static/imgs/bottomNav/shangjia1.png',
    title: '我的店铺',
    path: '/pages/shopManage',
    activeIcon: '../static/imgs/bottomNav/shangjia2.png',
  },
  {
    icon: '../static/imgs/bottomNav/dating1.png',
    title: '接单大厅',
    path: '/pages/OrderReceptionHall',
    activeIcon: '../static/imgs/bottomNav/dating2.png',
  },
  {
    icon: '../static/imgs/bottomNav/shouye1.png',
    title: '订单',
    path: '/pages/TakeoutOrder',
    activeIcon: '../static/imgs/bottomNav/shouye2.png',
  },
  {
    icon: '../static/imgs/bottomNav/wode1.png',
    title: '我的',
    path: '/pages/Mine',
    activeIcon: '../static/imgs/bottomNav/wode2.png',
  },
])
</script>

<style lang="scss">
.bottom-nav {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 120rpx;
  background-color: #fff;
  display: flex;
  align-items: center;
  justify-content: space-around;

  .bottom-nav-item {
    width: 25%;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;

    image {
      width: 40rpx;
      height: 39rpx;
      display: block;
    }

    label {
      display: block;
      font-weight: 400;
      font-size: 20rpx;
      color: #575859;
      line-height: 28rpx;
      text-align: left;
      font-style: normal;
      text-transform: none;
      margin-top: 5rpx;
    }

    // logo 特殊样式
    &.logo-item {
      label {
        display: none; // 隐藏 logo 下方的文字
      }

      image {
        width: 100rpx; // 保持原来的图片大小
        height: 100rpx;
      }
    }
  }
}

/* 店铺选择弹出层样式 */
.shop-popup {
  background-color: #fff;
  border-radius: 24rpx 24rpx 0 0;
  padding: 30rpx;

  .shop-popup-title {
    font-size: 32rpx;
    font-weight: bold;
    text-align: center;
    padding-bottom: 20rpx;
    border-bottom: 1px solid #f5f5f5;
    margin-bottom: 10rpx;
  }

  .shop-list {
    max-height: 60vh;
    overflow-y: auto;

    .shop-item {
      display: flex;
      align-items: center;
      padding: 24rpx 0;
      border-bottom: 1px solid #f5f5f5;

      .shop-logo {
        width: 80rpx;
        height: 80rpx;
        border-radius: 16rpx;
        margin-right: 20rpx;
      }

      .shop-info {
        flex: 1;

        .shop-name {
          font-size: 28rpx;
          font-weight: 500;
          color: #333;
          margin-bottom: 8rpx;
        }

        .shop-type {
          font-size: 24rpx;
          color: #999;
        }
      }
    }
  }

  .close-btn {
    margin-top: 30rpx;
    height: 80rpx;
    line-height: 80rpx;
    text-align: center;
    background: #f5f5f5;
    border-radius: 40rpx;
    font-size: 28rpx;
    color: #666;
  }
}
</style>
